<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="型材编号">
              <a-input placeholder="请输入型材编号" v-model="queryParam.materialCode"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="型材名称">
              <a-input placeholder="请输入型材名称" v-model="queryParam.materialName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="颜色">
              <a-input placeholder="请输入颜色" v-model="queryParam.color"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="状态">
              <j-dict-select-tag placeholder="请选择状态" v-model="queryParam.status" dictCode="wms_material_status" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchReset" icon="reload">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" v-if="hasPermission('wms:material:profile:add')"
        >新增</a-button
      >
      <a-button type="primary" icon="download" @click="handleExport" v-if="hasPermission('wms:material:profile:export')"
        >导出</a-button
      >
      <a-upload
        name="file"
        :showUploadList="false"
        :action="uploadUrl"
        :headers="tokenHeader"
        :data="{ materialType: '1' }"
        @change="handleImportChange"
        v-if="hasPermission('wms:material:profile:import')"
      >
        <a-button icon="import">导入</a-button>
      </a-upload>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel" v-if="hasPermission('wms:material:profile:delete')">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
        :scroll="{ x: 1700 }"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">查看明细</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

        <template slot="statusSlot" slot-scope="text">
          <a-tag :color="text == '0' ? 'green' : 'red'">
            <j-dict-label :value="text" dictCode="wms_material_status" />
          </a-tag>
        </template>

        <template slot="materialImageSlot" slot-scope="text">
          <span v-if="text">
            <img
              :src="getImageUrl(text)"
              height="30"
              alt="物料图片"
              @click="handlePreview(text)"
              style="cursor: pointer"
              @error="handleImageError"
            />
          </span>
          <span v-else>-</span>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 图片预览 -->
    <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
      <img alt="物料图片" style="width: 100%" :src="previewImage" />
    </a-modal>

    <!-- 表单区域 -->
    <material-modal ref="modalForm" @ok="modalFormOk"></material-modal>

    <!-- 物料明细 -->
    <material-detail-modal ref="detailModal"></material-detail-modal>
  </a-card>
</template>

<script>
import MaterialModal from './modules/MaterialModal'
import MaterialDetailModal from './modules/MaterialDetailModal'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JDictSelectTag from '@/components/dict/JDictSelectTag.vue'
import JDictLabel from '@/components/dict/JDictLabel.vue'
import { materialExport, materialImport } from '@/api/wms'
import { downFile, getFileAccessHttpUrl } from '@/api/manage'
import { USER_AUTH, SYS_BUTTON_AUTH } from '@/store/mutation-types'

export default {
  name: 'ProfileList',
  mixins: [JeecgListMixin],
  components: {
    MaterialModal,
    MaterialDetailModal,
    JDictSelectTag,
    JDictLabel,
  },
  data() {
    return {
      description: '型材管理',
      // 查询条件
      queryParam: {
        materialType: '1', // 默认查询型材类型
      },
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '型材编号',
          align: 'center',
          dataIndex: 'materialCode',
        },
        {
          title: '型材名称',
          align: 'center',
          dataIndex: 'materialName',
        },
        {
          title: '物料图片',
          align: 'center',
          dataIndex: 'materialImage',
          scopedSlots: { customRender: 'materialImageSlot' },
        },
        {
          title: '颜色',
          align: 'center',
          dataIndex: 'color',
        },
        {
          title: '长度(mm)',
          align: 'center',
          dataIndex: 'length',
        },
        {
          title: '宽度(mm)',
          align: 'center',
          dataIndex: 'width',
        },
        {
          title: '高度(mm)',
          align: 'center',
          dataIndex: 'height',
        },
        {
          title: '重量',
          align: 'center',
          dataIndex: 'weight',
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit',
        },
        {
          title: '单位成本',
          align: 'center',
          dataIndex: 'unitCost',
          customRender: (text) => {
            return text ? '¥' + parseFloat(text).toFixed(2) : '¥0.00'
          },
        },
        {
          title: '预警上限',
          align: 'center',
          dataIndex: 'upperLimit',
        },
        {
          title: '预警下限',
          align: 'center',
          dataIndex: 'lowerLimit',
        },
        {
          title: '余料上限',
          align: 'center',
          dataIndex: 'remnantUpper',
        },
        {
          title: '余料下限',
          align: 'center',
          dataIndex: 'remnantLower',
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'statusSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/wms/material/list',
        delete: '/wms/material/delete',
        deleteBatch: '/wms/material/deleteBatch',
        exportXlsUrl: materialExport,
      },
      // 上传相关
      uploadUrl: materialImport,
      // 权限相关
      permissionList: [],
      // 预览相关
      previewVisible: false,
      previewImage: '',
    }
  },
  created() {
    // 禁用mixin中的created钩子自动加载数据
    this.disableMixinCreated = true

    // 加载字典数据
    this.initDictConfig()

    // 页面加载时重置查询条件
    this.searchReset()

    // 添加默认的物料类型过滤
    this.queryParam.materialType = '1'
    // 获取权限列表
    this.loadPermissions()
    // 手动加载数据，确保带上materialType参数
    this.loadData()
  },
  methods: {
    // 加载权限
    loadPermissions() {
      console.log('开始加载权限列表')

      // 从sessionStorage获取权限
      let authList = JSON.parse(sessionStorage.getItem(USER_AUTH) || '[]')
      console.log('从sessionStorage获取的权限列表:', authList)

      // 如果sessionStorage中没有权限，尝试从localStorage获取
      if (!authList || authList.length === 0) {
        authList = JSON.parse(localStorage.getItem(USER_AUTH) || '[]')
        console.log('从localStorage获取的权限列表:', authList)
      }

      // 从按钮权限中获取
      const buttonAuth = JSON.parse(
        sessionStorage.getItem(SYS_BUTTON_AUTH) || localStorage.getItem(SYS_BUTTON_AUTH) || '[]'
      )
      console.log('按钮权限列表:', buttonAuth)

      // 合并权限
      if (buttonAuth && buttonAuth.length > 0) {
        authList = authList.concat(buttonAuth)
      }

      // 临时添加WMS相关权限用于测试
      const testPermissions = [
        { action: 'wms:material:profile:add' },
        { action: 'wms:material:profile:edit' },
        { action: 'wms:material:profile:delete' },
        { action: 'wms:material:profile:export' },
        { action: 'wms:material:profile:import' },
      ]
      authList = authList.concat(testPermissions)

      // 提取action字段
      this.permissionList = authList.map((auth) => auth.action || auth)
      console.log('最终权限列表:', this.permissionList)
    },

    // 判断是否有权限
    hasPermission(permission) {
      console.log(111111111111111111111111111111111111111111111111111111111)

      if (!permission) return true // 如果未指定权限，默认有权限

      console.log('检查权限:', permission)
      console.log('权限列表:', this.permissionList)
      console.log('检查权限列表中是否包含指定权限:', this.permissionList.includes(permission))

      // 检查权限列表中是否包含指定权限
      if (this.permissionList.includes(permission)) {
        return true
      }

      // 检查权限列表中是否包含以逗号分隔的多个权限
      for (let perm of this.permissionList) {
        if (perm && perm.includes(',')) {
          const perms = perm.split(',')
          if (perms.includes(permission)) {
            return true
          }
        }
      }

      return false
    },

    // 导出Excel
    handleExport() {
      if (!this.url.exportXlsUrl) {
        this.$message.error('请设置url.exportXlsUrl属性!')
        return
      }

      let params = this.getQueryParams() // 查询条件

      // 使用downFile函数导出Excel
      this.loading = true
      downFile(this.url.exportXlsUrl, params).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), '型材信息.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', '型材信息.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        }
        this.loading = false
      })
    },

    // 导入回调
    handleImportChange(info) {
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(info.file.response.message || '导入成功！')
          this.loadData()
        } else {
          this.$message.error(info.file.response.message || '导入失败！')
        }
      } else if (info.file.status === 'error') {
        this.$message.error('导入失败！')
      }
    },

    // 获取图片URL
    getImageUrl(text) {
      if (!text) return ''
      try {
        // 使用jeecg标准的文件访问方式
        return getFileAccessHttpUrl(text)
      } catch (error) {
        console.error('获取文件URL失败:', error)
        return ''
      }
    },

    // 预览图片
    handlePreview(text) {
      this.previewImage = this.getImageUrl(text)
      this.previewVisible = true
    },

    // 处理图片加载错误
    handleImageError(event) {
      console.error('图片加载失败', event)
      // 设置为空白图片
      event.target.src =
        ''
      event.target.alt = '图片加载失败'
    },

    handleDetail(record) {
      this.$refs.detailModal.show(record.id, record.materialName)
    },
    handleAdd() {
      this.$refs.modalForm.add('1') // 传入型材类型
    },
    handleEdit(record) {
      this.$refs.modalForm.edit(record)
    },
  },
}
</script>
